<!--
 * @Author: your name
 * @Date: 2021-04-02 17:26:09
 * @LastEditTime: 2021-06-06 10:07:23
 * @LastEditors: Please set LastEditors
 * @Description: 药企资讯
 * @FilePath: /medicine-web/src/views/realinfo/index.vue
-->
<template>
  <div class="real-info-container">
    <!-- <customBtn :btnStr="'数据统计'" @handClick="handleStatistics"></customBtn> -->
    <div class="document-container__result">
      <tabResultList :sortTabList="['时间']" :showDownloadAll="false" @checkAll="checkAll" @collectionAll="collectionAll" @sortStatus="sortStatus" :resultCount="total">
        <div slot="resultList" class="main-search__result-container">
          <div v-if="resultList && resultList.length > 0">
            <div class="main-search__result-item" v-for="item in resultList" :key="item.id">
              <a-checkbox v-model="item.isCheck" @change="onChange(item)"></a-checkbox>
              <ul class="main-search__result-content">
                <li @click.stop="navToCard(item)">
                  <span class="content-regex">{{item.title}}</span>
                </li>
                <li>
                  <span>病毒种类：<span class="content-regex">{{item.virus_type2}}</span></span>
                  <span style="margin-left: 40px;">产品名称：<span class="content-regex">{{item.drug_name}}</span></span>
                  <span style="margin-left: 40px;">药企名称：<span class="content-regex">{{item.company_name}}</span></span>
                </li>
                <li>
                  来源链接地址：<a style="color: #1890ff" :href="item.source_url" target="_blank" class="content-regex">{{item.source_url}}</a>
                </li>
                <li class="main-search__result-func">
                  <span>发表日期：<span class="content-regex">{{item.pubdate}}</span></span>
                  <span>
                    <userOptions :item="item" @handleClick="userClick"></userOptions>
                  </span>
                </li>
              </ul>
            </div>
          </div>
          <div v-else>
            <emptyData></emptyData>
          </div>
        </div>
      </tabResultList>
      <Pagation v-if="resultList && resultList.length > 0" v-model="pageNum" :total="total"  @handlePage="handlePage" style="margin-top: 48px"></Pagation>
    </div>
  </div>
</template>
<script>
import tabResultList from '@/components/TabResultList/index'
import customBtn from '@/components/CustomBtn/index'
import Pagation from '@/components/Pagation/index'
import userOptions from '@/components/UserOptions/index'
import { mapGetters } from 'vuex'
import { splitStrToArray, arrayToSplitStr, arrayToSplitStr1 } from '@/utils/index'
import emptyData from '@/components/EmptyData/index'
import share from '@/utils/share'
export default {
  name: 'realInfo',
  components: { customBtn, tabResultList, Pagation, userOptions, emptyData },
  data () {
    return {
      pageNum: 1,
      total: 0,
      resultList: [],
      checkList: [], // 被选择列表
      isInit: false, // 是否初始化
    }
  },
  methods: {
    checkAll (isCheck) {
      console.log('checkAll====================')
      this.resultList.map(item => {
        item.isCheck = isCheck
      })
      if (isCheck) {
        this.checkList = this.resultList
      } else {
        this.checkList = []
      }
    },
    async collectionAll () {
      if (!this.getCookie('uid')) {
        this.msgInfo('您还没有登录，正在跳转至登录界面...')
        setTimeout(() => {
          this.$router.push('/login')
        }, 1500)
        return
      }
      if (!this.checkList || this.checkList.length === 0) {
        this.msgInfo('请选择您要收藏的数据')
        return
      }
      const res = await this.$action('doCollection', { user_id: this.getCookie('uid'), ids: arrayToSplitStr1(this.checkList, 'id'), module: 3 })
      if (res) {
        this.msgSuccess('批量收藏成功')
        for (let item of this.resultList.filter(item => item.isCheck == true)) {
          item.isCollect = true
        }
      } else {
        this.msgError('批量收藏失败')
      }
    },
    sortStatus (sort) {
      if (sort.tab === '时间' && sort.active === false) {
        this.filterMap.order = 'pubdate'
        this.filterMap.order_by = 'asc'
      } else if (sort.tab === '时间' && sort.active === true) {
        this.filterMap.order = 'pubdate'
        this.filterMap.order_by = 'desc'
      }
      this.fetchData()
    },
    onChange (rawData) {
      console.log('onChange===========', rawData)
      if (rawData.isCheck) {
        this.checkList.push(rawData)
      } else {
        this.checkList = this.checkList.filter(item => item.id != rawData.id)
      }
    },
    // handleStatistics () {
    //   this.$router.push('/realinfo/statistics')
    // },
    handlePage (count) {
      console.log('handlePage=============', count)
      this.pageNum = count
      this.fetchData()
    },
    async userClick (rawData) {
      if (!this.getCookie('uid')) {
        this.msgInfo('您还没有登录，正在跳转至登录界面...')
        setTimeout(() => {
          this.$router.push('/login')
        }, 1500)
        return
      }
      console.log('userClick=============', rawData)
      if (rawData.type === 'collection') { // 收藏
        let res
        if (rawData.active) {
          res = await this.$action('doCollection', { user_id: this.getCookie('uid'), ids: rawData.data.id, module: 3 })
          if (res) {
            this.msgSuccess('收藏成功')
          } else {
            this.msgError('收藏失败')
          }
        } else {
          res = await this.$action('cancelCollection', { user_id: this.getCookie('uid'), id: rawData.data.id })
          if (res) {
            this.msgSuccess('取消收藏成功')
          } else {
            this.msgError('取消收藏失败')
          }
        }
      } else if (rawData.type === 'xinlang' && rawData.data.source_url) { // 分享新浪
        share.toShareXinLang(rawData.data.source_url, rawData.data.title)
      } else if (rawData.type === 'qq' && rawData.data.source_url) { // 分享QQ
        share.toShareQQZone(rawData.data.source_url, rawData.data.title, '', '')
      } else if (rawData.type === 'wechat' && rawData.data.source_url) { // 分享微信
        share.toShareWeChat(rawData.data.source_url)
      }
    },
    navToCard (item) {
      // this.$router.push({ path: '/realinfo/card', query: {id} })
      if (item && item.source_url) {
        const aLink = document.createElement('a')
        aLink.href = item.source_url
        aLink.target = '_blank'
        document.body.appendChild(aLink)
        aLink.click()
        document.body.removeChild(aLink)
      } else {
        this.msgInfo('暂无资源，无法进行跳转。')
      }
    },
    async fetchData () {
      let info = {
        limit: 10,
        page: this.pageNum
      }
      if (this.filterMap && Object.keys(this.filterMap).length > 0) {
        info = Object.assign(info, this.filterMap)
      }
      console.log('realinfo filter', info)
      const res = await this.$action('getRealInfoList', info)
      console.log('getRealInfoList', res)
      this.total = res.total_number || 0
      this.$action('setTotalNum', this.total)
      let dataList = res.data_list
      // this.$action('resetSort', true)
      if (!dataList || dataList.length === 0) {
        this.resultList = []
        return
      }
      dataList.map(item => {
        item.isShare = false
        item.isCheck = false
        item.isCollect = false
      })
      this.resultList = dataList
      console.log('getMaterialList map', this.resultList)
      if (this.searchValue) {
        this.$nextTick(() => {
          const contentEle = document.getElementsByClassName('content-regex')
          for (let item of contentEle) {
            const regex = new RegExp(this.searchValue, 'g')
            item.innerHTML = item.innerText
            item.innerHTML = item.innerHTML.replace(regex, '<b class="high-light" style="color: #FFBA00">' + this.searchValue + '</b>')
          }
          this.$forceUpdate()
        })
      }
    }
  },
  mounted () {
    this.isInit = true
    this.fetchData()
  },
  // beforeDestroy () {
  //   if (this.$route.path.indexOf('/simple/search') != -1) {
  //     return
  //   }
  //   this.$action('setFilter', {})
  // },
  computed: {
    ...mapGetters({
      filterMap: 'filterMap',
      searchValue: 'searchValue'
    })
  },
  watch: {
    filterMap: {
      handler (val, old) {
        if (val && val.keywords) {
          this.$nextTick(() => {
            const contentEle = document.getElementsByClassName('content-regex')
              for (let item of contentEle) {
              const regex = new RegExp(this.searchValue, 'g')
              item.innerHTML = item.innerText
              item.innerHTML = item.innerHTML.replace(regex, '<b class="high-light" style="color: #FFBA00">' + val.keywords + '</b>')
            }
            this.$forceUpdate()
          })
        }
        if (val.isInit == false) { // 搜索点击按钮
          this.isInit = val.isInit
        }
        if (this.isInit) {
          this.isInit = false
          return
        }
        this.pageNum = 1
        this.fetchData()
      },
      deep: true
    },
    searchValue: function (val, oldVal) {
      const contentEle = document.getElementsByClassName('content-regex')
      for (let item of contentEle) {
        const regex = new RegExp(val, 'g')
        item.innerHTML = item.innerText
        item.innerHTML = item.innerHTML.replace(regex, '<b class="high-light" style="color: #FFBA00">' + val + '</b>')
      }
    },
  }
}
</script>
<style lang="scss" scoped>
@import '~@/assets/styles/flex.scss';
@import '~@/assets/styles/common.scss';
.real-info-container {
  width: 1200px;
  margin: 0 auto;
  padding: 32px 0px 88px 0px;
  /deep/ .a-btn-container .btn-pattern {
    width: 132px;
    height: 37px;
    font-size: 14px;
    color: #555;
    background-color: #fff;
    border: 1px solid rgba(0, 0, 0, 0.21);
  }
  .document-container__result {
    // margin-top: 28px;
    .main-search__result-container {
      .main-search__result-item {
        @include flex-def;
        .main-search__result-content {
          width: 100%;
          margin-left: 8px;
          li:nth-child(n+2) {
            margin-top: 10px;
            font-size: 14px;
            color: #555;
          }
          li:nth-child(1) {
            font-size: 14px;
            color: #555;
            font-weight: bold;
            cursor: pointer;
          }
          .main-search__result-func {
            @include flex-def;
            @include flex-cCenter;
            @include flex-zBetween;
          }
        }
      }
    }
  }
}
</style>